using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;
using System.Xml.Serialization;

using Kryptiq.Ciq.Common.Extensions;
using Kryptiq.Network.OnRamp.Relay;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

using MvcContrib.ActionResults;

namespace SwitchServiceRole.Controllers
{
    public class SwitchController : Controller
    {
        public ActionResult Index()
        {
            var doc = XDocument.Load(Request.InputStream);

            XNamespace xmlns = "http://www.kryptiq.com/ciqnetwork";
            var actionElement = doc.Element(xmlns + "Envelope").Element(xmlns + "Body").Descendants().First();

            // we'll want to verify the header authorization prior to going on and passing in the account
            // now when necessary...
            return RedirectToAction(actionElement.Name.LocalName);
        }

        public XmlResult GetDirectory()
        {
            var urlHelper = new UrlHelper(ControllerContext.RequestContext);

            var host = Request.Headers["Host"];
            var downloadUri = new UriBuilder("http://" + host)
                                  {
                                      Scheme = Request.Url.Scheme,
                                      Path = urlHelper.Action("Download")
                                  };

            var response = EnvelopeFactory.CreateSuccessResponse();
            response.Body.Item = new CiqGetDirectoryResponse {DownloadUrl = downloadUri.ToString()};

            return new XmlResult(response);
        }

        public ActionResult Download()
        {
            CloudStorageAccount account = CloudStorageAccount.DevelopmentStorageAccount;

            CloudBlobClient blobClient = account.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference("directory-cache");

            var blob = container.GetBlobReference("Routes.xml");

            using (var ms = new MemoryStream())
            {
                blob.DownloadToStream(ms);
                ms.Position = 0;

                return new XmlResult(ms.FromXml<CiqDirectory>());
            }
        }
    }
}